#include <jthread.h>
//https://blog.csdn.net/maotoula/article/details/18501963#commentsedit

void *thread_proxy_func(void * args);

void* JThread::__run()
{
    threadStatus = THREAD_STATUS_RUNNING;
    tid = pthread_self();
    run();
    threadStatus = THREAD_STATUS_EXIT;
    tid = 0;
    pthread_exit(NULL);
}

JThread::JThread()
{
    tid = 0;
    threadStatus = THREAD_STATUS_NEW;
    flagRun = true;
}

bool JThread::start()
{
    return pthread_create(&tid, NULL, thread_proxy_func, this) == 0;
}

void JThread::stop()
{
    flagRun = false;
    clearResource();
}

void JThread::clearResource()
{
    //不需要清理
}

pthread_t JThread::getThreadID()
{
    return tid;
}

int JThread::getState()
{
    return threadStatus;
}

void *thread_proxy_func(void *args)
{
    JThread *pThread = static_cast<JThread *>(args);

    pThread->__run();

    return NULL;
}

void JThread::wait(unsigned long millisTime)
{
    if (tid == 0){
        return;
    }

    if (millisTime == 0){
        pthread_join(tid, NULL);
    }else{
        unsigned long k = 0;
        while (threadStatus != THREAD_STATUS_EXIT && k <= millisTime){
            usleep(100);
            k++;
        }
    }
}
